//
//  TPLoginViewController.m
//  CloudAtCostPanel
//
//  Created by leonardo on 2017/1/26.
//  Copyright © 2017年 tanpengsccd. All rights reserved.
//

#import "TPLoginViewController.h"
#import "UIViewController+TPUtility.h"
#import "TPUIKit.h"
#import "TPNetModel_Resources.h"
#import "TPNetModel_Delete.h"
#import "TPNetworkingManager.h"
#import <Masonry.h>
#import <LocalAuthentication/LocalAuthentication.h>
@interface TPLoginViewController ()
PRO_S TPLabelTextField * labelText_login;/**< 登陆邮箱 */
PRO_S TPLabelTextField * labelText_key; /**< 登陆APIKEY */
PRO_S TPButton * okBtn;

@end

@implementation TPLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"login";
    
    _labelText_login = [[TPLabelTextField alloc]initWithHorizonalLabelStr:@"Email:" textFieldPlaceHolderStr:[[NSUserDefaults standardUserDefaults] objectForKey:LOGIN]];
    _labelText_key = [[TPLabelTextField alloc]initWithHorizonalLabelStr:@"Key:" textFieldPlaceHolderStr:@""];
    self.okBtn = [[TPButton alloc]initwithNomalBtnTitleStr:@"login"];
    
    [self.view addSubview:self.labelText_login];
    [self.view addSubview:self.labelText_key];
    [self.view addSubview:self.okBtn];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    for (UIView * view in self.view.subviews) {
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view).offset(MARGIN_WINDOW);
            make.right.mas_equalTo(self.view).offset(-MARGIN_WINDOW);
        }];
    }
    
    [self.labelText_login mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(self.labelText_login.superview);
        make.top.mas_equalTo(self.labelText_login.superview).offset(MARGIN_WINDOW);
        make.height.mas_equalTo(HEIGHT_CELL);
    }];
    
    [self.labelText_key mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(self.labelText_key.superview);
        make.top.mas_equalTo(self.labelText_login.mas_bottom);
        make.height.mas_equalTo(HEIGHT_CELL);
    }];
    
    [self.okBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.labelText_key.mas_bottom).offset(MARGIN_CELL);
        make.height.mas_equalTo(HEIGHT_CELL);
    }];
#warning TO DELETE
   _labelText_login.textField.text = @"tanpengcd@gmail.com";
   _labelText_key.textField.text =  @"e3aRe1eJuvyDe8utYnUsY9a6y";
    //检测 指纹 是否开启
    LAContext * lacontext = [LAContext new];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:TOUCHIDLOGIN] isEqual:@1] && [lacontext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]) {
//        [self checkTouchIDLogin];
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [_okBtn addTarget:self action:@selector(tapOkBtn) forControlEvents:UIControlEventTouchUpInside];
}

- (void)tapOkBtn{

//    TPNetModel_Delete_req * req = [[TPNetModel_Delete_req alloc]init];
//    req.login = @"tanpengcd@gmail.com";
//    req.key = @"e3aRe1eJuvyDe8utYnUsY9a6y";
//    req.sid = @"254891652";
    TPNetModel_Resources_req * req =[[TPNetModel_Resources_req alloc]init];
        req.login = _labelText_login.textField.text;
        req.key = _labelText_key.textField.text;
    
   
    //普通CAC 请求
    
//    [[TPNetworkingManager manager] TP_Cac_POSTWithReqModel:req progress:nil successGetModel:^(id  _Nonnull responseObject) {
//        
//    } failureGetModel:^(id  _Nonnull responseObject) {
//        [self showHUDWithResModel_error:[TPBaseNetModel_res yy_modelWithDictionary:responseObject]];
//    }];
    
    //TPBaseViewController 基类 封装方法HUD 和 请求
    
    
    [self showHUDWithReqModel:req progress:nil successGetModel:^(TPBaseNetModel_res * res) {
        [[NSUserDefaults standardUserDefaults]setObject:req.login forKey:LOGIN];
        [[NSUserDefaults standardUserDefaults]setObject:req.key forKey:KEY];
        //后期尝试 使用realm 存储
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_GO_MAIN object:nil];
        
//        TPNetModel_Resources_res * res = res;
        DDLogDebug(@"%@",[res yy_modelDescription]);
    } failureGetModel:^(TPBaseNetModel_res * res) {
        [self showHudTipsWithResModel_error:res];
    }];
}

//-(void)checkTouchIDLogin{
//    //指纹解锁
//    LAContext *laContext = [[LAContext alloc] init];
//    
//    laContext.localizedFallbackTitle = @"";
//    NSError *error;
//    
//    if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
//        //        NSLog(@"laContext.evaluatedPolicyDomainState :%@",laContext.evaluatedPolicyDomainState);
//        [laContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
//                  localizedReason:@"以快速登录"
//                            reply:^(BOOL success, NSError *error) {
//                                if (success) {
//                                    NSLog(@"指纹验证成功");
//                                    //do your work
//                                    //                                    [[NSUserDefaults standardUserDefaults] setObject:@1 forKey:TOUCHIDLOGIN];
//                                    dispatch_async(dispatch_get_main_queue(), ^{
//                                        //                                        CustomAlertView * alert = [[CustomAlertView alloc]initWithTitle:@"指纹验证成功!\n已开启指纹快速登录功能\n您也可以在个人中心关闭指纹快速登录功能"];
//                                        //                                        [alert show];
//                                        _labelText_login.textField.text = [[NSUserDefaults standardUserDefaults] objectForKey:LOGIN];
//                                        _labelText_key.textField.text = [[NSUserDefaults standardUserDefaults] objectForKey:KEY];
//                                        [self tapOkBtn];
//                                    });
//                                    
//                                }
//                                if (error) {
//                                    //                                    [[NSUserDefaults standardUserDefaults] setObject:@0 forKey:TOUCHIDLOGIN];
//                                    
//                                    switch (error.code) {
//                                        case  LAErrorAuthenticationFailed:{
//                                            
//                                        }
//                                            break;
//                                            
//                                        case    LAErrorUserCancel:{
//                                            
//                                            
//                                            
//                                            
//                                            
//                                        }
//                                            break;
//                                            
//                                        case   LAErrorUserFallback:{
//                                            
//                                        }
//                                            break;
//                                            
//                                        case  LAErrorSystemCancel:{
//                                            
//                                        }
//                                            break;
//                                        case  LAErrorPasscodeNotSet:{
////                                            CustomAlertView * alert = [[CustomAlertView alloc]initWithTitle:@"您还未设置TouchID\n请前往设置中设置TouchID"];
////                                            [alert show];
//                                            TPAlertViewController * alert = [[TPAlertViewController sharedInstanceWithIdentifier:NSStringFromClass(self.class)]createOkWithTitle:@"Passcode is not set on the device !" subtitle:nil];
////                                            [self presentViewController:alert animated:YES completion:nil];
//                                            [alert showViewWithAnimated:YES];
//                                            //                                                [alert show];
//                                        }
//                                            break;
//                                        case  LAErrorTouchIDNotAvailable:{
//                                            
//                                        }
//                                            break;
//                                        case  LAErrorTouchIDNotEnrolled:{
//                                            
//                                        }
//                                            break;
//                                        case  LAErrorTouchIDLockout:{
//                                            dispatch_sync(dispatch_get_main_queue(), ^{
////                                                CustomAlertView * alert = [[CustomAlertView alloc]initWithTitle:@"无法识别您的指纹\n请输入密码登录"];
//                                                
//                                                TPAlertViewController * alert = [[TPAlertViewController sharedInstanceWithIdentifier:NSStringFromClass(self.class)]createOkWithTitle:@"Touch ID is now locked. Passcode is required to unlock Touch ID !" subtitle:nil];
////                                                [self presentViewController:alert animated:YES completion:nil];
//                                                [alert showViewWithAnimated:YES];
//                                            });
//                                            
//                                        }
//                                            break;
//                                        case  LAErrorAppCancel:{
//                                            
//                                        }
//                                            break;
//                                        case LAErrorInvalidContext:{
//                                            
//                                        }
//                                            break;
//                                            
//                                            
//                                        default:
//                                            break;
//                                    }
//                                    
//                                    
//                                    
//                                }
//                                
//                            }];
//    }
//    else {
//        NSLog(@"==========Not support :%@", error.description);
//        //do your error handle
//    }
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
